package classification;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.StringTokenizer;

import static utils.Configuration.*;

public class Dictionary
{
    /* Dictionary path */
    private static final String      ROOT       = RootPath;
    private static final String      DICT_PATH  = WordListFile;

    /* Dictionary is used to record idf information */
    private HashMap<String, Integer> dictionary = null;

    private static Dictionary        dict       = null;

    private int                      docNum     = 0;

    static public Dictionary getInstance()
    {
        if (dict == null)
        {
            dict = new Dictionary();
        }
        return dict;
    }

    private Dictionary()
    {
        this.dictionary = new HashMap<String, Integer>();
        this.loadDictionary();
    }

    private void loadDictionary()
    {
        try
        {
            FileReader fr = new FileReader(DICT_PATH);
            BufferedReader reader = new BufferedReader(fr);

            StringTokenizer stk = null;
            String line = "";
            String term = "";
            int freq = 0;

            /* 得到文件总数 */
            line = reader.readLine();
            stk = new StringTokenizer(line);
            String tmp = stk.nextToken();
            this.docNum = Integer.parseInt(stk.nextToken());

            /* 跳过class数目信息 */
            line = reader.readLine();

            /* 加载每个词的idf信息 */
            while ((line = reader.readLine()) != null)
            {
                stk = new StringTokenizer(line, ",");
                if(stk.countTokens() != 2)
                {
                    continue;
                }
                term = stk.nextToken();
                try
                {
                    freq = Integer.parseInt(stk.nextToken());
                }
                catch(Exception ex)
                {
                    continue;
                }

                this.dictionary.put(term, freq);
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public int getIDF(String key)
    {
        if (this.dictionary.containsKey(key))
        {
            return this.dictionary.get(key);
        }
        else
        {
            return 0;
        }
    }

    public HashMap<String, Integer> getDictionary()
    {
        return this.dictionary;
    }

    public int getDocumentNum()
    {
        return this.docNum;
    }

    public static void clear()
    {
        dict.dictionary = new HashMap<String, Integer>();
    }
}
